package com.example.demo.service;

import com.example.demo.model.CourseAccess;
import com.example.demo.model.Order;
import com.example.demo.repository.CourseAccessRepository;
import com.example.demo.repository.OrderRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class OrderService {
    @Autowired
    public OrderRepository orderRepo;
    @Autowired
    CourseAccessRepository accessRepo;
    @Autowired
    JavaMailSender mailSender;

    public Order createOrder(Long studentId, Long courseId, BigDecimal amount, String payMethod) {
        Order order = new Order();
        order.setStudentId(studentId);
        order.setCourseId(courseId);
        order.setAmount(amount);
        order.setStatus("pending");
        order.setPayMethod(payMethod);
        order.setCreatedAt(LocalDateTime.now());
        return orderRepo.save(order);
    }

    public void completePayment(Long orderId, String email) {
        Order order = orderRepo.findById(orderId).orElseThrow();
        order.setStatus("paid");
        order.setPaidAt(LocalDateTime.now());
        orderRepo.save(order);

        CourseAccess access = new CourseAccess();
        access.setStudentId(order.getStudentId());
        access.setCourseId(order.getCourseId());
        access.setAccessTime(LocalDateTime.now());
        accessRepo.save(access);

        sendSuccessMail(email);
    }

    private void sendSuccessMail(String to) {
        SimpleMailMessage msg = new SimpleMailMessage();
        msg.setTo(to);
        msg.setSubject("课程购买成功");
        msg.setText("您已成功购买课程，现在可以开始学习了！");
        mailSender.send(msg);
    }

    @Scheduled(fixedRate = 300000) // 每5分钟运行一次
    public void cancelTimeoutOrders() {
        List<Order> list = orderRepo.findByStatusAndCreatedAtBefore("pending", LocalDateTime.now().minusMinutes(30));
        for (Order o : list) {
            o.setStatus("canceled");
            orderRepo.save(o);
        }
    }
}